package com.rfid.project.web;

import java.text.DateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.ProjectFinishApply;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectFinishApplyService;
import com.rfid.project.service.ProjectTaskService;
import com.rfid.project.model.Project;
import com.rfid.project.service.ProjectService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;

@Controller
public class ProjectFinishApplyController {
	private static final Logger logger = LoggerFactory.getLogger(ProjectFinishApplyController.class);

	@Autowired
	private ProjectFinishApplyService projectFinishApplyService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private PeopleService peopleService;

	@Autowired
	private ProjectTaskService projectTaskService;

	@RequestMapping(value = "/projectFinishApplymgr")
	public String projectFinishApplymgr(HttpServletRequest request,
			HttpServletResponse response, Model model,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId) {
		Project project = this.projectService.findOne(projectId);
		model.addAttribute("project", project);

		boolean flag = this.projectTaskService.findWorkingByProject(project);
		model.addAttribute("workingProjectTasks", flag);
		return "projectFinishApplymgr";
	}

	@RequestMapping(value = "/queryProjectFinishApply")
	public String queryProjectFinishApply(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "applyPersonId", defaultValue = "-1") Long applyPersonId,
			@RequestParam(value = "applyReason", defaultValue = "") String applyReason,
			@RequestParam(value = "applyTimeBegin", defaultValue = "") Date applyTimeBegin,
			@RequestParam(value = "applyTimeEnd", defaultValue = "") Date applyTimeEnd,
			@RequestParam(value = "checkPersonId", defaultValue = "-1") Long checkPersonId,
			@RequestParam(value = "checkDescription", defaultValue = "") String checkDescription,
			@RequestParam(value = "checkTimeBegin", defaultValue = "") Date checkTimeBegin,
			@RequestParam(value = "checkTimeEnd", defaultValue = "") Date checkTimeEnd,
			@RequestParam(value = "ratifyPersonId", defaultValue = "-1") Long ratifyPersonId,
			@RequestParam(value = "ratifyDescription", defaultValue = "") String ratifyDescription,
			@RequestParam(value = "ratifyTimeBegin", defaultValue = "") Date ratifyTimeBegin,
			@RequestParam(value = "ratifyTimeEnd", defaultValue = "") Date ratifyTimeEnd,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectFinishApply> projectFinishApplys = projectFinishApplyService
				.findAll(projectId, applyPersonId, applyReason, applyTimeBegin,
						applyTimeEnd, checkPersonId, checkDescription,
						checkTimeBegin, checkTimeEnd, ratifyPersonId,
						ratifyDescription, ratifyTimeBegin, ratifyTimeEnd,
						status, pageNumber, pageSize, sort, order);
		JSONObject object = new JSONObject();
		object.put("total", projectFinishApplys.getTotalElements());
		JSONArray models = new JSONArray();
		for (ProjectFinishApply item : projectFinishApplys) {
			JSONObject mod = new JSONObject();
			mod.put("id", item.getId());
			mod.put("checkTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getCheckTime()));
			
			String checkContent = item.getCheckDescription();
			mod.put("checkDescription", checkContent == null ? "" : checkContent);
			mod.put("status", ProcessStatus.processStatusName(item.getStatus()));
			mod.put("statusCode", item.getStatus());
			mod.put("applyTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getApplyTime()));
			mod.put("applyReason", item.getApplyReason());
			mod.put("ratifyTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getRatifyTime()));
			
			String ratifyContent = item.getRatifyDescription();
			mod.put("ratifyDescription", ratifyContent == null ? "" : ratifyContent);

			mod.put("projectId", item.getProject().getId());
			mod.put("projectName", item.getProject().getName());

			People applyErson = item.getApplyPerson();
			mod.put("applyPersonId", applyErson.getId());
			mod.put("applyPersonName", applyErson.getName());

			People checkPerson = item.getCheckPerson();
			if (null != checkPerson) {
				mod.put("checkPersonId", checkPerson.getId());
				mod.put("checkPersonName", checkPerson.getName());
			} else {
				mod.put("checkPersonId", -1);
				mod.put("checkPersonName", "");
			}

			People ratifyPerson = item.getRatifyPerson();
			if (null != ratifyPerson) {
				mod.put("ratifyPersonId", ratifyPerson.getId());
				mod.put("ratifyPersonName", ratifyPerson.getName());
			} else {
				mod.put("ratifyPersonId", -1);
				mod.put("ratifyPersonName", "");
			}

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}

	@RequestMapping(value = "/getProjectFinishApply")
	public String getProjectFinishApply(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id) {
		ProjectFinishApply item = projectFinishApplyService.getProjectFinishApply(id);
		JSONObject mod = new JSONObject();
		mod.put("id", item.getId());
		mod.put("checkTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getCheckTime()));
		mod.put("checkDescription", item.getCheckDescription());
		mod.put("status", item.getStatus());
		mod.put("applyTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getApplyTime()));
		mod.put("applyReason", item.getApplyReason());
		mod.put("ratifyTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getRatifyTime()));
		mod.put("ratifyDescription", item.getRatifyDescription());
		mod.put("planConsumeWorkTime", item.getProject().getPlanConsumeWorkTime());
		mod.put("actualConsumeWorktime", item.getProject().getActualConsumeWorktime());

		mod.put("projectId", item.getProject().getId());
		mod.put("projectName", item.getProject().getName());

		People applyErson = item.getApplyPerson();
		mod.put("applyPersonId", applyErson.getId());
		mod.put("applyPersonName", applyErson.getName());

		People checkPerson = item.getCheckPerson();
		if (null != checkPerson) {
			mod.put("checkPersonId", checkPerson.getId());
			mod.put("checkPersonName", checkPerson.getName());
		} else {
			mod.put("checkPersonId", -1);
			mod.put("checkPersonName", "");
		}

		People ratifyPerson = item.getRatifyPerson();
		if (null != ratifyPerson) {
			mod.put("ratifyPersonId", ratifyPerson.getId());
			mod.put("ratifyPersonName", ratifyPerson.getName());
		} else {
			mod.put("ratifyPersonId", -1);
			mod.put("ratifyPersonName", "");
		}
		PageJsonBean.printObject(response, mod);
		return null;
	}

	@RequestMapping(value = "/editProjectFinishApply", method = RequestMethod.POST)
	public String editProjectFinishApply(HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectFinishApply projectFinishApply, Model model,
			RedirectAttributes redirectAttributes) {
		People applyPerson = projectFinishApply.getApplyPerson();
		if(null == applyPerson || null == applyPerson.getId()){
			projectFinishApply.setApplyPerson((People)request.getSession().getAttribute("currentUser"));
		}
		projectFinishApplyService.saveProjectFinishApply(projectFinishApply);
		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/checkProjectFinishApply", method = RequestMethod.POST)
	public String checkProjectFinishApply(
			HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectFinishApply projectFinishApply,
			Model model, RedirectAttributes redirectAttributes) {
		People checkPerson = projectFinishApply.getCheckPerson();
		if (null == checkPerson || null == checkPerson.getId()) {
			projectFinishApply.setCheckPerson((People) request.getSession().getAttribute("currentUser"));
		}
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			projectFinishApplyService.checkProjectFinishApply(projectFinishApply);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/ratifyProjectFinishApply", method = RequestMethod.POST)
	public String ratifyProjectFinishApply(
			HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectFinishApply projectFinishApply,
			Model model, RedirectAttributes redirectAttributes) {
		People ratifyPerson = projectFinishApply.getRatifyPerson();
		if (null == ratifyPerson || null == ratifyPerson.getId()) {
			projectFinishApply.setRatifyPerson((People) request.getSession().getAttribute("currentUser"));
		}
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			projectFinishApplyService.ratifyProjectFinishApply(projectFinishApply);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProjectFinishApply")
	public String delProjectFinishApply(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.projectFinishApplyService.deleteProjectFinishApply(id);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/revocationFinishApplyProjectFinishApply")
	public String revocationFinishApplyProjectFinishApply(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectFinishApply projectFinishApply,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectFinishApplyService.revocationFinishApplyProjectDelayApply(projectFinishApply);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
}
